import asyncio
import websockets
import logging
from voice_assistant.my_state import app_state
from voice_assistant.ws.audio_handler import send_audio_data
from voice_assistant.ws.message_handler import handle_message
from voice_assistant.config_manager import config_manager

logger = logging.getLogger("WebSocket")

async def async_websocket_client():
    """异步WebSocket客户端"""
    logger.info("启动异步WebSocket客户端...")
    
    while True:
        app_state.server_connected = False
        reconnect_delay = min(
            config_manager.get("server.reconnect_base_delay") * (2 ** min(app_state.reconnect_count, 10)),
            config_manager.get("server.max_reconnect_delay")
        )
        
        if app_state.reconnect_count > 0:
            logger.info(f"重连尝试 {app_state.reconnect_count}，等待 {reconnect_delay:.1f}秒后重连...")
            await asyncio.sleep(reconnect_delay)
        
        try:
            ws_server = config_manager.get("server.ws_url")
            logger.info(f"尝试连接到服务器: {ws_server}")
            async with websockets.connect(ws_server) as ws:
                app_state.ws_connection = ws
                app_state.server_connected = True
                app_state.reconnect_count = 0
                logger.info(f"成功连接到服务器 {ws_server}")
                
                receive_task = asyncio.create_task(handle_message(ws))
                send_task = asyncio.create_task(send_audio_data(ws))
                await asyncio.gather(send_task, receive_task)
                
        except (ConnectionRefusedError, websockets.exceptions.InvalidURI, OSError) as e:
            logger.warning(f"服务器连接失败: {str(e)}")
            app_state.reconnect_count += 1
            app_state.connection_error = f"连接错误: {str(e)}"
        except asyncio.TimeoutError:
            logger.warning(f"连接服务器超时")
            app_state.reconnect_count += 1
            app_state.connection_error = "连接超时"
        except websockets.exceptions.ConnectionClosed as e:
            logger.warning(f"连接被关闭: {e.reason if e.reason else '未知原因'}")
            app_state.reconnect_count += 1
            app_state.connection_error = f"连接关闭: {e.reason if e.reason else '未知原因'}"
        except Exception as e:
            logger.error(f"意外连接错误: {str(e)}")
            app_state.reconnect_count += 1
            app_state.connection_error = f"未知错误: {str(e)}"
        finally:
            app_state.server_connected = False
            app_state.ws_connection = None

def run_async_websocket():
    """在新线程中运行异步事件循环"""
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    loop.run_until_complete(async_websocket_client())